/// Author: Samle
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'dart:convert' as convert;
import '../../../routes/app_pages.dart'; /// lib/app/routes/app_pages.dart
import '../../../../db/db_helper.dart';
import '../../../../store/page_store.dart';

class WordsController extends GetxController with StateMixin<List> {
  RxList wordsList = [].obs;
  RxMap bookForm = {}.obs;
  GlobalKey<FormState> wordsKey = GlobalKey<FormState>();
  TextEditingController search = TextEditingController();
  /// 引入状态管理
  PageStore _pageStore = PageStore();
  /// 获取缓存数据
  getStoreData() async {
    paramsForm = await _pageStore.getWordsParamsForm();
    dataForm = await _pageStore.getWordsDataForm();
  }

  /// 查询参数集
  Map paramsForm = {
    "pageSize": 50,
    "pageNum": 1,
    "search" : null,
    "id": null,
    "name": null,
    "trans": null,
    "belong": null,
    "checkTimes": null,
    "errorTimes": null,
    "helpText": null,
    "soundText": null,
  };
  reStr(String oldStr){
    String newStr = oldStr.replaceAll("'", "''");
    return newStr;
  }
  /// 获取 Words 数据集
  getWordsList() async {
    if (Get.arguments.isNotEmpty && Get.arguments != null && Get.arguments.containsKey('bookId')){
      paramsForm["belong"] = ',' + Get.arguments['bookId'].toString() + ',';
      bookForm.value = await localData.getBooksById(Get.arguments['bookId']);
    }
    /// 传入查询参数 <其他参数按需传入>
    paramsForm["search"] = reStr(search.text);
    paramsForm["pageSize"] = 50;
    paramsForm["pageNum"] = 1;
    /// 将查询参数集存储到状态管理中
    await _pageStore.setWordsParamsForm(paramsForm);
    /// 进行查询
    wordsList.value = await localData.getWordsBySearch(paramsForm);
    change(wordsList, status: RxStatus.success());

    // wordsList.value = await localData.getWords();
    // change(wordsList, status: RxStatus.success());
  }
  /// 获取 Words 数据集分页
  Future<void> getWordsListMore() async {
    if (Get.arguments.isNotEmpty && Get.arguments != null && Get.arguments.containsKey('bookId')){
      paramsForm["belong"] = ',' + Get.arguments['bookId'].toString() + ',';
    }
    paramsForm["search"] = reStr(search.text);
    paramsForm["pageSize"] = 50;
    paramsForm["pageNum"] = paramsForm["pageNum"] + 1;
    /// 进行查询
    var moreValue = await localData.getWordsBySearch(paramsForm);
    if (moreValue.isNotEmpty) {
      wordsList.value.addAll(moreValue);
      change(wordsList, status: RxStatus.success());
    } else {
      if (paramsForm["pageNum"] > 1) {
        paramsForm["pageNum"] = paramsForm["pageNum"] - 1;
      }
      Fluttertoast.showToast(
        msg: "已经到底了！",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        backgroundColor: Colors.black12,
        textColor: Colors.black54,
        fontSize: 16.0,
      );
    }
  }

  /// 数据表单
  Map dataForm = {
    "id": null,
    "name": null,
    "trans": null,
    "ukphone": null,
    "ukspeech": null,
    "usphone": null,
    "usspeech": null,
    "syno": null,
    "relWord": null,
    "sentence": null,
    "phrase": null,
    "exam": null,
    "belong": null,
    "checkTimes": null,
    "errorTimes": null,
    "helpText": null,
    "soundText": null,
  };

  /// 跳转编辑界面 按需要修改路由
  toEditPage() {
    Get.toNamed('/edit-words', arguments: dataForm)?.then((value) async {
      if (value == null) { return; } else {
        if (value.containsKey("id") && value['id'] != null && value['id'] != ''){
          dataForm = value;
          updateWords();
        } else {
          dataForm = value;
          addWords();
        }
      }
    });
  }

  /// 修改 Words 实例
  updateWords() async {
    /// 更新 dataForm 数据
    /// dataForm = newDataForm;
    /// 将表单数据存储到状态管理中
    await _pageStore.setWordsDataForm(dataForm);
    try {
      var result = await localData.updateWords(dataForm);
      /// Get.back(result: true); // 更新成功后回调
      dataForm = cleanDataForm;
      await _pageStore.setWordsDataForm(dataForm);
      Fluttertoast.showToast(
        msg: "更新成功！",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        backgroundColor: Colors.green,
        textColor: Colors.white,
        fontSize: 16.0,
      );
      onInit();
    } catch (e) {
      /// 更新失败后回调
      Fluttertoast.showToast(
        msg: "更新失败！",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0,
      );
    }
  }

  /// 新增 Words 实例
  addWords() async {
    /// 更新 dataForm 数据
    /// dataForm = newDataForm;
    /// 将表单数据存储到状态管理中
    await _pageStore.setWordsDataForm(dataForm);
    try {
      var result = await localData.addWords(dataForm);
      /// Get.back(result: true); // 新增成功后回调
      dataForm = cleanDataForm;
      await _pageStore.setWordsDataForm(dataForm);
      Fluttertoast.showToast(
        msg: "新增成功！",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        backgroundColor: Colors.green,
        textColor: Colors.white,
        fontSize: 16.0,
      );
      onInit();
    } catch (e) {
      /// 新增失败后回调
      Fluttertoast.showToast(
        msg: "新增失败！",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0,
      );
    }
  }

  /// 数据表单
  Map cleanDataForm = {
    "id": null,
    "name": null,
    "trans": null,
    "ukphone": null,
    "ukspeech": null,
    "usphone": null,
    "usspeech": null,
    "syno": null,
    "relWord": null,
    "sentence": null,
    "phrase": null,
    "exam": null,
    "belong": null,
    "checkTimes": null,
    "errorTimes": null,
    "helpText": null,
    "soundText": null,
  };

  /// 删除 Words 实例
  delWords(form) async {
    if (form.containsKey("id") && form["id"] != ""){
      try {
        var result = await localData.deleteWords(form["id"]);
        /// Get.back(result: true); // 删除成功后回调
        Fluttertoast.showToast(
          msg: "删除成功！",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          backgroundColor: Colors.green,
          textColor: Colors.white,
          fontSize: 16.0,
        );
        onInit();
      } catch (e) {
        /// 删除失败后回调
        Fluttertoast.showToast(
          msg: "删除失败！",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          fontSize: 16.0,
        );
      }
    }
  }

  @override
  Future<void> onInit() async {
    await getStoreData();
    await getWordsList();
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }
}
